#coding=utf-8
import urllib
from BeautifulSoup import BeautifulSoup

def google_cn(query):
    query = query.encode('u8')
    url = "http://www.google.cn/complete/search?hl=zh-CN&xhr=t&q=%s&cp=%i"%(urllib.quote(query), len(query))
    #print url
    data = eval( urllib.urlopen(url).read())
    
    if type(data) != type([]):
        print "error"
        return None
    if not data[1]:return None
    
    result = [unicode(d[0], 'u8') for d in data[1]]
    return result
    
def google_com(query):
    query = query.encode('u8')
    url = "http://clients1.google.com/complete/search?hl=en&q=%s"%(urllib.quote(query))
    data = urllib.urlopen(url).read()
    
    try:
        data = eval(data.split('(')[1][:-1])
    except:
        print "%s:error"%query
        return None
        
    if type(data) != type([]):
        print "error"
        return None
        
    if not data[1]:return None
    
    result = [unicode(d[0], 'u8') for d in data[1]]
    return result
    
def yahoo_cn(query):
    query = query.encode('u8')
    url = 'http://www.yahoo.cn/homepage/suggestion.inc.php?query=%s'%(urllib.quote(query))
    data = urllib.urlopen(url).read()
    data = data.split('|')
    if not data or not data[0]:return None
    data = [unicode(d, 'u8') for d in data]
    return data
    
def yahoo_com(query):
    query = query.encode('u8')
    
    url = 'http://sugg.search.yahoo.net/sg/?output=fxjsonp&nresults=10&command=%s'%(urllib.quote(query))
    
    data = urllib.urlopen(url).read()
    try:
        data = eval(data.split('(')[1].split(')')[0])[1]
    except:
        print "error"
        return None
    
    if not data:return None
    data = [unicode(d, 'u8') for d in data]
    return data

def ask(query):
    query = query.encode('u8')
    url = 'http://ss.ask.com/query?fn=suggestCallBack&q=%s'%(urllib.quote(query))
    
    data = urllib.urlopen(url).read()
    try:
        data = eval(data.split('(')[1][:-1])['Suggestions']    
    except:
        print "error"
        return None
        
    if not data:return None
    data = [unicode(d, 'u8') for d in data]
    return data

def baidu(query):

    query = query.encode('gbk')
    url = 'http://toolbar.baidu.com/sobar/rs.php?q=%s'%(urllib.quote(query))
    data = urllib.urlopen(url).read()
    #print data
    bs = BeautifulSoup(unicode(data, 'gbk'))
    #print bs
    try:
        result = [r['words']for r in bs.findAll('record')]
    except:
        print "error"
        return None
    if not result:return None    
    return result

if __name__ == '__main__':
    #测试
    fs = [google_cn, yahoo_cn, yahoo_com, ask, baidu]
    data = ['harvard', 'alfjadjfoiawj', unicode('中', 'u8')]
    for f in fs:
        print '\n%s'%f.__name__
        for d in data:
            r = f(d)
            print d
            if not r: 
                print ':None'
            else:
                for i in r:
                    print i,
                print
                
    
